//
//  CustomerAlert.m
//  Auction
//
//  Created by Gary on 15/9/21.
//  Copyright © 2015年 Lebo. All rights reserved.
//

#import "CustomerAlert.h"
#import "Common.h"

static const CGFloat kCenterCornerRadius   = 12.f;
static const CGFloat kCloseSide            = 34.f;//关闭按钮边长
static const CGFloat kSubViewMargin        = 40.f;
static const CGFloat kTitleHeight          = 25.f;
static const CGFloat kHtmlViewMarginTop    = 10.f;
static const CGFloat kHtmlViewMarginBottom = 10.f;
#define kTitleFont MakeFontBold(18.f)
#define kConfirmButtonTitleFont1 MakeFontBold(18.f)
#define kConfirmButtonTitleFont2 MakeFontBold(16.f)

static CustomerAlert *sharedInstance;

@interface CustomerAlert () {
    UIView *_centerView;
    UIButton *_closeButton;
}

@end

@implementation CustomerAlert

+ (CustomerAlert *)sharedInstance {
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        sharedInstance = [[[self class] alloc] init];
    });
    return sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self initView];
    }
    return self;
}

- (void)initView {
    self.frame = MakeRect(0, 0, ScreenWidth, ScreenHeight);
    UIButton *bg = [[UIButton alloc] initWithFrame:self.bounds];
    [self addSubview:bg];
    
    bg.backgroundColor = kMaskBackgroundColor;
    bg.alpha = kMaskAlpha;
    [bg addTarget:self
           action:@selector(hide)
 forControlEvents:(UIControlEventTouchUpInside)];
    
    _centerView = [[UIView alloc] init];
    _centerView.backgroundColor = [UIColor whiteColor];
    _centerView.layer.cornerRadius = kCenterCornerRadius;
    _centerView.clipsToBounds = YES;
    _centerView.userInteractionEnabled = YES;
    [self addSubview:_centerView];
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

+ (CGFloat)subViewWidth {
    return ScreenWidth - kSubViewMargin;
}

+ (UILabel *)titleLabel:(NSString *)title {
    if (![Common isEmptyString:title]) {
        UILabel *label = [[UILabel alloc] initWithFrame:MakeRect(0,
                                                                 kCustomerAlertPaddingTop,
                                                                 [CustomerAlert subViewWidth],
                                                                 kTitleHeight)];
        label.font = kTitleFont;
        label.text = title;
        label.textAlignment = NSTextAlignmentCenter;
        return label;
    }
    return nil;
}

+ (DTAttributedLabel *)htmlView:(id)htmlText {
    DTAttributedLabel *label = [[DTAttributedLabel alloc] initWithFrame:MakeRect(kCustomerAlertPaddingHorizontal,
                                                                                 0,
                                                                                 [CustomerAlert subViewWidth] - 2 * kCustomerAlertPaddingHorizontal,
                                                                                 CGFLOAT_HEIGHT_UNKNOWN)];
    label.numberOfLines = 0;
    if ([htmlText isKindOfClass:NSString.class]) {
        label.attributedString = [Common attrStrFromHtmlText:htmlText];
    } else if ([htmlText isKindOfClass:NSMutableAttributedString.class]) {
        label.attributedString = htmlText;
    }
    return label;
}

+ (UIButton *)confirmButton {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = MakeRect(0, 0, [CustomerAlert subViewWidth], kTableCellHeight);
    button.backgroundColor = kNavigartionBarBgColor;
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [button setTitle:LocalStr(@"CommonTitleConfirm") forState:UIControlStateNormal];
    button.titleLabel.font = kConfirmButtonTitleFont1;
    [button addTarget:[CustomerAlert sharedInstance]
               action:@selector(hide)
     forControlEvents:UIControlEventTouchUpInside];
    return button;
}

+ (void)setButton:(UIButton *)button properties:(NSDictionary *)properties {
    id target = nil;
    id selector = nil;
    for (NSString *key in properties.allKeys) {
        if ([kCustomerAlertPropertyKeyTitle isEqualToString:key]) {//按钮标题文字
            [button setTitle:properties[key] forState:UIControlStateNormal];
        } else if ([kCustomerAlertPropertyKeyTarget isEqualToString:key]) {//按钮事件的target
            target = properties[key];
        } else if ([kCustomerAlertPropertyKeyAction isEqualToString:key]) {//按钮事件的action
            selector = properties[key];
        } else if ([kCustomerAlertPropertyKeyFont isEqualToString:key]) {//按钮标题的字体
            button.titleLabel.font = properties[key];
        } else if ([kCustomerAlertPropertyKeyColor isEqualToString:key]) {//按钮标题的字体颜色
            [button setTitleColor:properties[key] forState:UIControlStateNormal];
        } else if ([kCustomerAlertPropertyKeyBGColor isEqualToString:key]) {//按钮的背景颜色
            button.backgroundColor = properties[key];
        }
    }
    if (target && selector) {
        [button removeTarget:[CustomerAlert sharedInstance]
                      action:@selector(hide)
            forControlEvents:UIControlEventTouchUpInside];
        SEL action;
        [selector getValue:&action];
        [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    }
}

- (void)hide {
    [self removeFromSuperview];
    for (UIView *view in _centerView.subviews) {
        [view removeFromSuperview];
    }
    _closeButton = nil;
}

- (void)addViewToCenter:(UIView *)view {
    CGFloat width = ViewWidth(view);
    CGFloat height = ViewHeight(view);
    _centerView.frame = MakeRect((ScreenWidth - width) / 2.f,
                                 (ScreenHeight - height) / 2.f, width, height);
    _closeButton.center =
    CGPointMake(ViewRight(_centerView), _centerView.frame.origin.y);
    [_centerView addSubview:view];
}

- (void)showCloseButton {
    if (!_closeButton) {
        _closeButton =
        [[UIButton alloc] initWithFrame:MakeRect(0, 0, kCloseSide, kCloseSide)];
        [_closeButton setBackgroundImage:[UIImage imageNamed:@"customer_close"]
                                forState:UIControlStateNormal];
        _closeButton.center =
        CGPointMake(ViewRight(_centerView), _centerView.frame.origin.y);
        [_closeButton addTarget:self
                         action:@selector(hide)
               forControlEvents:(UIControlEventTouchUpInside)];
        
        [self addSubview:_closeButton];
    }
}

- (NSArray *)bottomButtons:(id)properties {
    if ([properties isKindOfClass:NSString.class]) {
        //如果参数是字符串，那么就是单个按钮的标题
        UIButton *confirmButton = [CustomerAlert confirmButton];
        [confirmButton setTitle:(NSString *)properties forState:UIControlStateNormal];
        return @[confirmButton];
    } else if ([properties isKindOfClass:NSDictionary.class]) {
        //如果参数是字典，那么就是单个按钮的属性，属性值包括按钮颜色、按钮文字和按钮事件等，具体可查看setButton函数
        UIButton *confirmButton = [CustomerAlert confirmButton];
        [CustomerAlert setButton:confirmButton properties:properties];
        return @[confirmButton];
    } else if ([properties isKindOfClass:NSArray.class]) {
        //多个按钮样式的设置
        NSMutableArray *arr = [NSMutableArray array];
        NSArray *propertyArr = properties;
        NSUInteger count = propertyArr.count;
        CGFloat width = [Common customerAlertMaxWidth];
        CGFloat buttonWidth = width / count;
        for (int i = 0; i < count; i++) {
            //默认的样式
            UIButton *button = [CustomerAlert confirmButton];
            if (count > 1) {
                button.frame = MakeRect(i * buttonWidth, 0, buttonWidth, ViewHeight(button));
                button.backgroundColor = [UIColor clearColor];
                [button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
                button.titleLabel.font = kConfirmButtonTitleFont2;
                //添加上方线
                UIView *topLine = [[UIView alloc] initWithFrame:MakeRect(0, 0, buttonWidth, kSeperatorLineThickness)];
                topLine.backgroundColor = kSeperatorLineColor;
                [button addSubview:topLine];
                if (i != 0) {
                    //添加左边线
                    UIView *leftLine = [[UIView alloc] initWithFrame:MakeRect(0, 0, kSeperatorLineThickness, ViewHeight(button))];
                    leftLine.backgroundColor = kSeperatorLineColor;
                    [button addSubview:leftLine];
                }
                if (count == 2 && i == 1) {//两个按钮有特殊的默认样式
                    [button setTitleColor:kConfirmButtonColorHighlighted forState:UIControlStateNormal];
                }
            }
            
            id property = propertyArr[i];
            if ([property isKindOfClass:NSString.class]) {
                //定制的按钮标题文字
                [button setTitle:(NSString *)properties forState:UIControlStateNormal];
            } else if ([property isKindOfClass:NSDictionary.class]) {
                //定制的按钮属性
                [CustomerAlert setButton:button properties:property];
            }
            
            [arr addObject:button];
        }
        return [NSArray arrayWithArray:arr];
    }
    
    return @[];
}

- (void)showTitle:(id)title htmlText:(NSString *)htmlText {
    [self showTitle:title
           htmlText:htmlText
             height:CGFLOAT_HEIGHT_UNKNOWN
   buttonProperties:LocalStr(@"CommonTitleConfirm")];
}

- (void)showTitle:(id)title htmlText:(NSString *)htmlText height:(CGFloat)height {
    [self showTitle:title
           htmlText:htmlText
             height:height
   buttonProperties:LocalStr(@"CommonTitleConfirm")];
}


- (void)showTitle:(id)title
         htmlText:(NSString *)htmlText
 buttonProperties:(id)buttonProperties {
    [self showTitle:title
           htmlText:htmlText
             height:CGFLOAT_HEIGHT_UNKNOWN
   buttonProperties:buttonProperties];
}

- (void)showTitle:(id)title
         htmlText:(NSString *)htmlText
           height:(CGFloat)height
 buttonProperties:(id)buttonProperties {
    if (htmlText) {
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor whiteColor];
        DTAttributedLabel *label = [CustomerAlert htmlView:htmlText];
        [view addSubview:label];
        CGFloat labelHeight = (height == CGFLOAT_HEIGHT_UNKNOWN) ? [label intrinsicContentSize].height : height;
        label.frame = MakeRect(label.frame.origin.x,
                               label.frame.origin.y,
                               ViewWidth(label),
                               labelHeight);
        view.frame = MakeRect(0, 0, [CustomerAlert subViewWidth], ViewHeight(label));
        [self showTitle:[CustomerAlert titleLabel:title]
                   view:view
                buttons:[self bottomButtons:buttonProperties]];
    }
}

- (void)showTitle:(UILabel *)title view:(UIView *)view buttons:(NSArray *)buttons {
    UIView *bgView = [[UIView alloc] initWithFrame:MakeRect(0, 0, [CustomerAlert subViewWidth], CGFLOAT_HEIGHT_UNKNOWN)];
    bgView.backgroundColor = [UIColor clearColor];
    bgView.userInteractionEnabled = YES;
    
    if (title) {
        [bgView addSubview:title];
        view.frame = MakeRect(0,
                              ViewBottom(title) + kHtmlViewMarginTop,
                              ViewWidth(view),
                              ViewHeight(view));
    } else {
        view.frame = MakeRect(0, kCustomerAlertPaddingTop, ViewWidth(view), ViewHeight(view));
    }
    [bgView addSubview:view];
    
    UIView *bottomView = [[UIView alloc] init];
    [bgView addSubview:bottomView];
    bottomView.backgroundColor = [UIColor clearColor];
    bottomView.userInteractionEnabled = YES;
    
    CGFloat buttonHeight = 0.f;
    for (UIButton *button in buttons) {
        [bottomView addSubview:button];
        buttonHeight = (buttonHeight >= ViewHeight(button)) ? buttonHeight : ViewHeight(button);
    }
    bottomView.frame = MakeRect(0, ViewBottom(view) + kHtmlViewMarginBottom, [CustomerAlert subViewWidth], buttonHeight);
    bgView.frame = MakeRect(0, 0, [CustomerAlert subViewWidth], ViewBottom(bottomView));
    [self addViewToCenter:bgView];
    [[[UIApplication sharedApplication] keyWindow] addSubview:self];
}

@end
